<?php

namespace Iwesen\Sem\Track\Advertisers;

use Illuminate\Support\Facades\Log;

class Sm
{
    protected $api =  "https://e.sm.cn/api/uploadConversions";

    public function callback($param)
    {
        if(!isset($param['username']) || !$param['username']){
            $param['username'] = config('sem-track.sm.username');
            if(!$param['username']){
                throw new \Exception( 'username is not a exist !');
            }
        }
        if(!isset($param['password']) || !$param['password']){
            $param['password'] = config('sem-track.sm.password');
            if(!$param['password']){
                throw new \Exception( 'password is not a exist !');
            }
        }
        if(!isset($param['source']) || !$param['source']){
            $param['source'] = config('sem-track.sm.source');
            if(!$param['source']){
                $param['source']=0;
            }
        }

        if(!isset($param['data']) || !is_array($param['data'])){
            throw new \Exception( 'data is not a exist !');
        }
        //验证转化类型并补全
        foreach($param['data'] as $k=>$cv){
            if(!is_array($cv)){
                throw new \Exception( 'data presentation error !'); 
            }
            if(!isset($cv['click_id'])||!$cv['click_id']){
                throw new \Exception( 'click_id  is not a exist !'); 
            }
            if(!isset($cv['conv_type'])||!$cv['conv_type']){
                $param['data'][$k]['conv_type']=config('sem-track.sm.conv_type');
            }
            if(!isset($cv['conv_name'])||!$cv['conv_name']){
                $param['data'][$k]['conv_name']=config('sem-track.sm.conv_name');
            }
            if(!isset($cv['conv_value'])||!$cv['conv_value']){
                $param['data'][$k]['conv_value']=config('sem-track.sm.conv_value');
            }
            $param['data'][$k]['date']=now()->toDateString();
        }
        //构建请求数据
        $postData = [
            'header'=>[
                'username'=>$param['username'],
                'password'=>$param['password'],
            ],
            'body'=>[
                'source'=>$param['source'],
                'data'=>$param['data']
            ]
        ];
        try {
            $result = (new Request())->_request($this->api,'',$postData);
            $data = json_decode($result,true);
            $status = $data['header']['status'];
            if ($status === 0) {
                return 'success';
            }
            return $data['header']['desc'];
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), $e->getCode(), $e);
        } 
    }
}